package Er

import (
	"errors"
	"fmt"
	dm "db2s/Dm"
	greatdb "db2s/Gr"
	sqlserver "db2s/Ms"
	mysql "db2s/My"
	oracle "db2s/Or"
	"reflect"
	"strings"
)

type ConnActive struct {
	DBType string
}

var (
	ConnActiveApi = map[string]any{
		"mysql":     &mysql.ConnActive{},
		"oracle":    &oracle.ConnActive{},
		"cluster":   &greatdb.ConnActive{},
		"sqlserver": &sqlserver.ConnActive{},
		"dm":        &dm.Conn{},
	}
)

func CActive(s ConnActive) (t TableConnEr, err error) {
	mutex.Lock()
	defer mutex.Unlock()
	Func, ok := dbTypeInterFuncRef[s.DBType]
	if !ok {
		return nil, errors.New(fmt.Sprintf("input database type error. input is {%v} What is expected is {%v}", s.DBType, func() string {
			var p []string
			for k := range dbTypeInterFuncRef {
				p = append(p, k)
			}
			return strings.Join(p, ",")
		}()))
	}
	if Func.Kind() != reflect.Func {
		return
	}
	args := []reflect.Value{
		reflect.ValueOf(s),
		reflect.ValueOf(ConnActiveApi[s.DBType]),
	}
	i := Func.Call(args)
	for ii := 0; ii < len(i); ii++ {
		t = i[ii].Interface().(TableConnEr)
	}
	return
}
